import math
import pygame
from setting import *
from pygame import gfxdraw
"""
杨辉三角的数的规律
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
……
"""


def YangHui(n):
    #初设化，并赋值为0,建立二维数组，res[i][i],i=0~n-1;
    # 其实也可以直接建立 res[n][n]数组。
    res = [[0 for i in range(j + 1)] for j in range(n)]
    #左右两边赋值1
    for i in range(0, n):
        res[i][0] = 1
        res[i][i] = 1
    #从第二个数开始，等于前列的左边一个加上正上方一个
    for row in range(1, n):
        for col in range(1, row):
            res[row][col] = res[row - 1][col - 1] + res[row - 1][col]
    return res


def bezier(points, t):
    n = len(points)
    pointx = 0
    pointy = 0
    nrow_a = YangHui(n)
    for v in range(0, n):
        c = v
        b = n - 1 - c
        a = nrow_a[n - 1][v]
        # print('a:', a, "b:", b, "c:", c)
        # print(points[v][0], points[v][1])
        pointx += a * math.pow((1 - t), b) * math.pow(t, c) * points[v][0]
        pointy += a * math.pow((1 - t), b) * math.pow(t, c) * points[v][1]
    return pointx, pointy


def main():

    surf = pygame.display.set_mode((600, 800), 1, 32)
    pygame.display.set_caption("贝塞尔曲线测试")
    surf.fill((0, 0, 0))
    #四个测试点
    points = [(-10, -10), (200, 800), (300, 200), (1000, 200)]
    #pygame提供的函数
    col = (255, 0, 0)
    pygame.gfxdraw.bezier(surf, points, 10, col)
    #画直线
    col2 = (0, 255, 0)
    pygame.draw.line(surf, col2, (10, 40), (200, 400), 10)
    pygame.draw.line(surf, col2, ((200, 400)), (450, 200), 10)
    pygame.draw.line(surf, col2, ((450, 200)), (100, 30), 10)
    #自己编写的函数实现
    col3 = (0, 0, 255)
    point2 = []
    for v in range(0, 5):
        t = v / 5
        point2.append(bezier(points, t))
    for v in range(1, 5):
        pygame.draw.line(surf, col3, point2[v - 1], point2[v], 1)
    pygame.display.flip()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()


main()